/**
 * @author 0283000115
 * @date 2018年3月3日-下午2:32:37
 */
package com.zte.claa.inficombo.csa.app.controller;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.zte.claa.inficombo.csa.app.controller.ret.ApiResult;
import com.zte.claa.inficombo.csa.app.model.redis.DevMeteData;
import com.zte.claa.inficombo.csa.app.service.resrpt.ResIndexDataRptService;

import io.swagger.annotations.ApiOperation;

/**
 * @author 0283000115
 * 
 * 该controller仅用于接收化工园测点数据上报.
 *
 */

@RestController
@RequestMapping("/csa/whp") 
public class WhpResIndexDataRptController extends BaseController {
	// 时间戳格式.
	public static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
	// WHP上报数据的公共字段... 
	public static final String COLLECT_TIME = "collecttime";
	public static final String RES_EUI = "deveui";
	
	// logger
	private Logger logger = LoggerFactory.getLogger(WhpResIndexDataRptController.class);
	// 时间格式化...
	// private SimpleDateFormat dtFormater = new SimpleDateFormat(DATETIME_FORMAT);
	
	@Autowired
	private ResIndexDataRptService resDataRptService;
	
	/**
	 * DCS数据上报.
	 */
	@ApiOperation(value = "WHP-DCS单个指标上报", notes = "化工园DCS系统单个指标上报")
	@RequestMapping(value={"/resonedatarpt"})
	@ResponseBody
	public ApiResult<?> resOnedatarpt(HttpServletRequest request) throws Exception{		
		ApiResult<String> ret = new ApiResult<String>();
		String jsonStr = "";
		try{
			jsonStr = this.getJsonParam(request);
			logger.info("[one]Receive json str: "+jsonStr);
			JSONObject json = new JSONObject(jsonStr);
			DevMeteData devMeteData = this.parseJson2Metedata(json);
			this.resDataRptService.submitResIndexData(devMeteData);	
			ret.setResult(ApiResult.RET_SUCC);
			ret.setRemark("");
		}catch(Exception e){
			logger.error("resOnedatarpt process failed: "+jsonStr, e);
			ret.setResult(ApiResult.RET_FAIL);
			ret.setRemark(e.getMessage());
		}
		return ret;		
	}
	
	/**
	 * DCS数据上报.
	 */
	@ApiOperation(value = "WHP-DCS指标批量上报", notes = "化工园DCS系统指标批量上报")
	@RequestMapping(value={"/resdatarpt"})
	@ResponseBody
	public ApiResult<?> resdatabatchrpt(HttpServletRequest request) throws Exception{		
		ApiResult<String> ret = new ApiResult<String>();
		String jsonStr = "";
		try{
			jsonStr = this.getJsonParam(request);
			logger.info("[batch]Receive json str: "+jsonStr);
			JSONArray jsonArr = new JSONArray(jsonStr);
			int num = jsonArr.length();
			for(int i=0; i<num; i++){
				JSONObject json = jsonArr.getJSONObject(i);
				DevMeteData devMeteData = this.parseJson2Metedata(json);
				this.resDataRptService.submitResIndexData(devMeteData);	
			}
			logger.info("Finish process {} rpt data.", num);
			ret.setResult(ApiResult.RET_SUCC);
			ret.setRemark("");
		}catch(Exception e){
			logger.error("resdatabatchrpt process failed: "+jsonStr, e);
			ret.setResult(ApiResult.RET_FAIL);
			ret.setRemark(e.getMessage());
		}
		return ret;		
	}
	
	// 解析单个metedata对象. 
	private DevMeteData parseJson2Metedata(JSONObject json) throws Exception {
		HashMap<String, Object> data = new HashMap<String, Object>();
		Iterator<?> it = json.keys();
		// 遍历jsonObject数据，添加到Map对象
		while (it.hasNext()) {
			String key = String.valueOf(it.next());
			Object value = json.get(key);
			data.put(key, value);
		}
		DevMeteData devMeteData = new DevMeteData();
		devMeteData.setDeveui(data.remove(RES_EUI).toString());
		Object rptTsObj = data.remove(COLLECT_TIME);
		if(rptTsObj != null && !rptTsObj.toString().equals("")){
			try{
				SimpleDateFormat dtFormater = new SimpleDateFormat(DATETIME_FORMAT);
				Date rptts = dtFormater.parse(rptTsObj.toString());
				devMeteData.setRpttime(new Timestamp(rptts.getTime()));
			}catch(Exception ignore){}
		}
		devMeteData.setMdata(data);
		return devMeteData;
	}
	
}
